<!DOCTYPE html>
<html>
<head>
    <!-- 页面meta -->
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>传智健康</title>
    <meta name="description" content="传智健康">
    <meta name="keywords" content="传智健康">
    <meta content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" name="viewport">
    <!-- 引入样式 -->
    <link rel="stylesheet" href="../plugins/elementui/index.css">
    <link rel="stylesheet" href="../plugins/font-awesome/css/font-awesome.min.css">
    <link rel="stylesheet" href="../css/style.css">
    <style>
        .datatable {
            position: relative;
            box-sizing: border-box;
            -webkit-box-flex: 1;
            width: 100%;
            max-width: 100%;
            font-size: 14px;
            color: rgb(96, 98, 102);
            overflow: hidden;
            flex: 1 1 0%;
        }

        .datatable td, .datatable th {
            padding: 12px 0;
            min-width: 0;
            -webkit-box-sizing: border-box;
            box-sizing: border-box;
            text-overflow: ellipsis;
            vertical-align: middle;
            position: relative;
            text-align: left;
        }


    </style>
</head>
<body class="hold-transition">
<div id="app">
    <div class="content-header">
        <h1>系统管理
            <small>菜单管理</small>
        </h1>
        <el-breadcrumb separator-class="el-icon-arrow-right" class="breadcrumb">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>系统管理</el-breadcrumb-item>
            <el-breadcrumb-item>菜单管理</el-breadcrumb-item>
        </el-breadcrumb>
    </div>
    <div class="app-container">
        <div class="box">
            <div class="filter-container">
                <el-input placeholder="菜单名称" v-model="pagination.queryString" style="width: 200px;"
                          class="filter-item"></el-input>
                <!--
                v-if="permission.MENU_QUERY"
                v-if="permission.MENU_ADD"
                -->
                <el-button @click="handleCurrentChange(1)" class="dalfBut">查询</el-button>
                <el-button type="primary" class="butT" @click="handleCreate()">新建</el-button>
            </div>

            <el-table
                    :data="tableData"
                    style="width: 100%;margin-bottom: 20px;"
                    row-key="id"
                    border
                    lazy="lazy"
                    @expand-change="expandChange"
                    :load="load"
                    :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
                <el-table-column prop="name" label="菜单名称" align="center"></el-table-column>
                <el-table-column prop="linkUrl" label="访问路径" align="center"></el-table-column>
                <el-table-column prop="priority" label="路径级别" align="center"></el-table-column>
                <el-table-column prop="parentMenuId" label="自关联Id" align="center"></el-table-column>
                <el-table-column prop="level" label="菜单级别" align="center"></el-table-column>
                <el-table-column prop="hasLoad" label="是否加载" v-if="false" align="center"></el-table-column>
                <el-table-column label="操作" align="center">
                    <!--
                    v-if="permission.MENU_EDIT"
                    v-if="permission.MENU_DELETE"
                    -->
                    <template slot-scope="scope">
                        <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
                        <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!--分页插件-->
            <div class="pagination-container">
                <el-pagination
                        class="pagiantion"
                        @current-change="handleCurrentChange"
                        :current-page="pagination.currentPage"
                        :page-size="pagination.pageSize"
                        layout="total, prev, pager, next, jumper"
                        :total="pagination.total">
                </el-pagination>
            </div>
            <!-- 新增菜单弹层 -->
            <div class="add-form">
                <el-dialog title="新增菜单项" :visible.sync="dialogFormVisible">
                    <template>
                        <el-form label-position="right" label-width="100px"
                                 ref="dataAddForm" :model="formData"
                                 :rules="rules">
                            <el-row>
                                <el-col :span="12">
                                    <el-form-item label="菜单名称" prop="name">
                                        <el-input v-model="formData.name"/>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="访问路径" prop="linkUrl">
                                        <el-input v-model="formData.linkUrl" placeholder="格式：xxx.html 一级菜单不填"/>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row>
                                <el-col :span="12">
                                    <el-form-item label="路径级别" prop="path">
                                        <el-input v-model="formData.path" placeholder="格式：1 一级路径 /1-1 二级路径"/>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="优先级" prop="priority">
                                        <el-input v-model="formData.priority" placeholder="大于0的整数"/>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row>
                                <el-col :span="12">
                                    <el-form-item label="自关联Id" prop="parentMenuId">
                                        <el-select v-model="formData.parentMenuId" placeholder="请选择关联的菜单">
                                            <el-option v-for="item in menus"
                                                       :label="item.label" :value="item.value">
                                            </el-option>
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="菜单级别" prop="level">
                                        <el-input v-model="formData.level" placeholder="大于0的整数"/>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row>
                                <el-col :span="24">
                                    <el-form-item label="图标">
                                        <el-input v-model="formData.icon"></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row>
                                <el-col :span="24">
                                    <el-form-item label="注意事项">
                                        <el-input v-model="formData.remark" type="textarea"></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </el-form>
                    </template>
                    <div slot="footer" class="dialog-footer">
                        <el-button @click="dialogFormVisible = false">取消</el-button>
                        <el-button type="primary" @click="handleAdd()">确定</el-button>
                    </div>
                </el-dialog>
            </div>
            <!-- 编辑菜单弹层 -->
            <div class="edit-form">
                <el-dialog title="编辑菜单" :visible.sync="dialogFormVisible4Edit">
                    <template>
                        <el-form label-position="right" label-width="100px"
                                 ref="dataAddForm" :model="editFormData"
                                 :rules="rules">
                            <el-row>
                                <el-col :span="12">
                                    <el-form-item label="菜单名称" prop="name">
                                        <el-input v-model="editFormData.name"/>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="访问路径" prop="linkUrl">
                                        <el-input v-model="editFormData.linkUrl"/>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row>
                                <el-col :span="12">
                                    <el-form-item label="路径级别" prop="path">
                                        <el-input v-model="editFormData.path"/>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="优先级" prop="priority">
                                        <el-input v-model="editFormData.priority"/>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row>
                                <el-col :span="12">
                                    <el-form-item label="自关联Id" prop="parentMenuId">
                                        <el-select v-model="editFormData.parentMenuId" placeholder="请选择关联的菜单">
                                            <el-option v-for="item in menus"
                                                       :label="item.label" :value="item.value">
                                            </el-option>
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="菜单级别" prop="level">
                                        <el-input v-model="editFormData.level"/>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row>
                                <el-col :span="24">
                                    <el-form-item label="图标">
                                        <el-input v-model="editFormData.icon"></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row>
                                <el-col :span="24">
                                    <el-form-item label="注意事项">
                                        <el-input v-model="editFormData.remark" type="textarea"></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </el-form>

                    </template>
                    <div slot="footer" class="dialog-footer">
                        <el-button @click="dialogFormVisible4Edit = false">取消</el-button>
                        <el-button type="primary" @click="handleEdit()">确定</el-button>
                    </div>
                </el-dialog>
            </div>

        </div>
    </div>
</div>
</body>
<!-- 引入组件库 -->
<script src="../js/vue.js"></script>
<!-- 引入样式 -->
<link rel="stylesheet" href="../element-ui/lib/theme-chalk/index.css">
<!-- 引入组件库 -->
<script src="../element-ui/lib/index.js"></script>
<!--<script src="../plugins/elementui/index11.js"></script>-->
<script type="text/javascript" src="../js/jquery.min.js"></script>
<script src="../js/axios-0.18.0.js"></script>

<script>
    var vue = new Vue({
        el: '#app',
        data: {
            //本页面按钮显示需要的权限
            /*permission:{
            },*/

            pagination: {//分页相关模型数据
                currentPage: 1,//当前页码
                pageSize: 10,//每页显示的记录数
                total: 0,//总记录数
                queryString: null//查询条件
            },
            tableData: [],//当前页要展示的分页列表数据
            menus: [],//新增和编辑表单中角色对应的复选框，基于双向绑定可以进行回显和数据提交
            formData: {},//添加表单数据
            editFormData: {},//编辑表单数据
            dialogFormVisible: false,//增加表单是否可见
            dialogFormVisible4Edit: false,//编辑表单是否可见
            rules: {//校验规则
                name: [{required: true, message: '菜单名称为必填项', trigger: 'blur'}],
                linkUrl: [{required: false, message: '访问路径为必填项', trigger: 'blur'}],
                path: [{required: true, message: '路径级别为必填项', trigger: 'blur'}],
                priority: [{required: true, message: '优先级为必填项', trigger: 'blur'}],
                parentMenuId: [{required: false, message: '自关联Id为必填项', trigger: 'blur'}],
                level: [{required: true, message: '菜单级别为必填项', trigger: 'blur'}],
            },
            openEdit: false,//一个标志变量,标记为是否打开编辑表单
            formDataChange: false,//一个标志变量,标记编辑表单中的数据是否发生改变
            formDataContain: {},//创建一个容器,用于存储编辑表单的数据回显
            deepCloneObj: {}//创建一个容器,用于深拷贝一份编辑表单数据回显的数据
        },
        //钩子函数，VUE对象初始化完成后自动执行
        created() {
            //发送ajax请求向后端获取到该用户拥有的权限
            /*axios.post("/permissionserver/findAllPermission.do").then((res) => {
                this.permission = res.data;
            });*/

            this.findPage();
        },
        methods: {
            //树展开和收起的回调函数
            expandChange(row, isExpand) {
                console.log("_______________")
                console.log(row);
                if (row.hasLoad) { //已经加载过
                    let myLength;
                    let _this = this;
                    axios.post("/menu/findChildrenMenu.do?parentMenuId=" + row.id).then((res) => {
                        myLength = res.data.data.length;
                        if (!isExpand) {//合并
                            _this.pagination.total -= myLength;
                        }else {//展开
                            _this.pagination.total += myLength;
                        }
                        _this.pagination.pageSize =_this.pagination.total;
                    })


                }
            },
            //分页查询
            findPage() {

                let _this = this;
                //将分页的参数进行封装
                let param = {
                    pageSize: this.pagination.pageSize,
                    currentPage: this.pagination.currentPage,
                    queryString: this.pagination.queryString
                };
                //post异步将数据传到controller
                axios.post("/menu/findPage.do", param).then((res) => {
                    //获取服务器响应的数据，封装了 总条数，数据的集合
                    _this.pagination.total = res.data.total;
                    _this.tableData = res.data.rows
                    console.log()
                })
            },
            load(tree, treeNode, resolve) {
                console.log(tree)
                console.log(treeNode)
                console.log("---------------------")
                axios.post("/menu/findChildrenMenu.do?parentMenuId=" + tree.id).then((res) => {
                    //获取服务器响应的数据，封装了 总条数，数据的集合
                    tree.hasLoad = true;
                    resolve(res.data.data)
                });
            },
            // 重置表单
            resetForm() {
                this.formData = {};
            },
            // 弹出添加窗口
            handleCreate() {
                this.dialogFormVisible = true;
                this.resetForm();
                //查询所有的关联菜单名称
                axios.get("/menu/findByName.do").then((res) => {
                    if (res.data.flag) {
                        this.menus = res.data.data;
                    } else {//执行失败
                        this.$message.error(res.data.message);
                    }
                });
                this.$refs['dataAddForm'].clearValidate();//清除表格的校验提示
            },

            //添加
            handleAdd: function () {
                /*console.log(this.formData);*/
                //在进行添加的时候先对，表单进行校验，防止因为不填写数据，直接保存的空数据
                this.$refs['dataAddForm'].validate((valid) => {
                    if (valid) {
                        //隐藏添加的窗口
                        this.dialogFormVisible = false;
                        //异步将数据传递
                        axios.post("/menu/add.do", this.formData).then((res) => {
                            if (res.data.flag) {
                                this.findPage();
                                this.$message.success(res.data.message)
                            } else {//执行失败
                                this.$message.error(res.data.message);
                            }
                        })
                    } else {
                        //校验不通过
                        this.$message.error("数据校验不通过，请重新输入");
                        return false;
                    }
                });

            },

            // 弹出编辑窗口
            handleUpdate(row) {
                //弹出编辑窗口
                this.dialogFormVisible4Edit = true;
                //将编辑editFormData中的数据清空
                this.editFormData = {};
                //判断是否开启编辑窗口
                this.openEdit = true;
                //将数据进行深度拷贝，监听器会触发 watch
                this.editFormData = this.deepClone(row);
                //将数据进行深度拷贝，监听器会触发 watch
                this.deepCloneObj = this.deepClone(row);
                //这里可以不写
                this.formDataChange = false;

                //查询所有的关联菜单名称
                axios.get("/menu/findbyName.do").then((res) => {
                    if (res.data.flag) {
                        this.menus = res.data.data;
                    } else {//执行失败
                        this.$message.error(res.data.message);
                    }
                });
                this.$refs['dataAddForm'].clearValidate();//清除表格的校验提示
            },
            //编辑
            handleEdit() {
                //判断数据有没有发生改变，watch中调用方法 判断两者是否完全相等
                if (!this.formDataChange) {
                    this.$message("数据没有改变");
                    return;
                }
                //表单校验
                //注意：注意：ajax都是异步操作，所以findPage方法要放finally里面
                this.$refs['dataAddForm'].validate((valid) => {
                    if (valid) {
                        //axios发生ajax请求
                        axios.post("/menu/edit.do", this.editFormData).then((res) => {
                            if (res.data.flag) {
                                this.$message.success(res.data.message);
                            } else {
                                this.$message.error(res.data.message);
                            }
                        }).finally(() => {//不管成功与失败都要进行查询
                            this.findPage();
                            this.dialogFormVisible4Edit = false;
                        })
                    } else {
                        this.$message.error("表单数据校验失败");
                    }
                });
            },

            // 删除
            handleDelete(row) {
                this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    axios.get("/menu/findRoleBymid.do?id=" + row.id).then((res) => {
                        if (res.data.flag) {
                            this.$confirm(res.data.message)
                        } else {
                            this.deletemenu(row);
                        }
                    }).finally(() => {
                        this.findPage();
                    })
                });
            },

            /*//删除菜单
            deletemenu(row) {
                axios.get("/menu/deletemenu.do?id=" + row.id).then((res) => {
                    if (res.data.flag) {
                        this.$message.success(res.data.message)
                    } else {
                        this.$message.error(res.data.message);
                    }
                }).catch((r) => { //axios对象请求的catch， 网络请求不是2xx
                    this.showMessage(r);
                }).finally(() => {
                    this.findPage();
                })
            },*/


            //深拷贝
            deepClone(obj) {
                /*  let target = {};
                for (let key in obj) {
                    if (Object.prototype.hasOwnProperty.call(obj, key)) {
                        if (typeof obj[key] === 'object') {
                            target[key] = this.deepClone(obj[key]);
                        } else {
                                target[key] = obj[key];
                        }
                    }
                }
                return target;
*/
                if (obj === null) return null;
                if (typeof obj != 'object') return obj;
                if (obj.constructor === Date) return new Date(obj);
                let target = new obj.constructor();
                for (let key in obj) {
                    if (obj.hasOwnProperty(key)) {
                        let val = obj[key];
                        target[key] = typeof val === 'object' ? arguments.callee(val) : val;
                    }
                }
                return target;
                /* return JSON.parse(JSON.stringify(obj));*/
                //这样的意思是，将obj进行序列化，保存到磁盘上，ran后通过反序列化，再获取到该对象，该对象将是个新对象，并不会影响到原来的
                // 这样写也是有问题的，
                // 1.如果有时间对象，时间对象会被转换成一个字符串
                //2.如果有正则表达式，或者error对象，序列化会为空
                //3.如果对象中有循环引用无法实现正常拷贝
            },
            //切换页码
            handleCurrentChange(currentPage) {

                this.pagination.currentPage = currentPage;
                this.findPage();
            },

            showMessage(r) {
                if (r == 'Error: Request failed with status code 403') {
                    //权限不足
                    this.$message.error('无访问权限');

                } else {
                    this.$message.error('未知错误');

                }
            },


            //判断对象值是否相等
            isObjectValueEqual(x, y) {
                var i, l, leftChain, rightChain;

                function compare2Objects(x, y) {
                    var p;

                    // remember that NaN === NaN returns false
                    // and isNaN(undefined) returns true
                    if (isNaN(x) && isNaN(y) && typeof x === 'number' && typeof y === 'number') {
                        return true;
                    }

                    // Compare primitives and functions.
                    // Check if both arguments link to the same object.
                    // Especially useful on the step where we compare prototypes
                    if (x === y) {
                        return true;
                    }

                    // Works in case when functions are created in constructor.
                    // Comparing dates is a common scenario. Another built-ins?
                    // We can even handle functions passed across iframes
                    if ((typeof x === 'function' && typeof y === 'function') ||
                        (x instanceof Date && y instanceof Date) ||
                        (x instanceof RegExp && y instanceof RegExp) ||
                        (x instanceof String && y instanceof String) ||
                        (x instanceof Number && y instanceof Number)) {
                        return x.toString() === y.toString();
                    }

                    // At last checking prototypes as good as we can
                    if (!(x instanceof Object && y instanceof Object)) {
                        return false;
                    }

                    if (x.isPrototypeOf(y) || y.isPrototypeOf(x)) {
                        return false;
                    }

                    if (x.constructor !== y.constructor) {
                        return false;
                    }

                    if (x.prototype !== y.prototype) {
                        return false;
                    }

                    // Check for infinitive linking loops
                    if (leftChain.indexOf(x) > -1 || rightChain.indexOf(y) > -1) {
                        return false;
                    }

                    // Quick checking of one object being a subset of another.
                    // todo: cache the structure of arguments[0] for performance
                    for (p in y) {
                        if (y.hasOwnProperty(p) !== x.hasOwnProperty(p)) {
                            return false;
                        } else if (typeof y[p] !== typeof x[p]) {
                            return false;
                        }
                    }

                    for (p in x) {
                        if (y.hasOwnProperty(p) !== x.hasOwnProperty(p)) {
                            return false;
                        } else if (typeof y[p] !== typeof x[p]) {
                            return false;
                        }

                        switch (typeof (x[p])) {
                            case 'object':
                            case 'function':

                                leftChain.push(x);
                                rightChain.push(y);

                                if (!compare2Objects(x[p], y[p])) {
                                    return false;
                                }

                                leftChain.pop();
                                rightChain.pop();
                                break;

                            default:
                                if (x[p] !== y[p]) {
                                    return false;
                                }
                                break;
                        }
                    }

                    return true;
                }

                if (arguments.length < 1) {
                    return true; //Die silently? Don't know how to handle such case, please help...
                    // throw "Need two or more arguments to compare";
                }

                for (i = 1, l = arguments.length; i < l; i++) {

                    leftChain = []; //Todo: this can be cached
                    rightChain = [];

                    if (!compare2Objects(arguments[0], arguments[i])) {
                        return false;
                    }
                }

                return true;
            }
        },
        watch: {//监听器 当指定的数据发生改变时 记录 第一次不记录
            editFormData: {
                deep: true,//深度监听 当为复杂的对象时，比如user 当username发生改变时，也能监听到
                handler: function (newVal, oldVal) {
                    if (this.openEdit) {
                        this.openEdit = false;
                        return;
                    }
                    this.formDataChange = !this.isObjectValueEqual(newVal, this.deepCloneObj);
                }
            }
        }
    })
</script>
</html>
